package com.nut.controller;

import com.nut.entity.Article;
import com.nut.entity.User;
import com.nut.service.ArticleService;
import com.nut.service.UserService;
import com.nut.vo.Message;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-04-23 13:52
 * @ Description : 文章controller
 */

@Controller
@CrossOrigin
@RequestMapping("/article")
public class ArticleController
{
    @Autowired
    private ArticleService articleService;

    @Autowired
    private UserService userService;

    /**
     * @Description 获取所有User的所有Article
     * @param 
     * @return 
     **/
    @ResponseBody
    @RequestMapping("/findAll")
    public Message getAllUserArticles()
    {
        List<User> allUsers = userService.findAllUsers();
        for (User allUser : allUsers)
        {
            allUser.setArticles(articleService.findAllArticles(allUser));
        }

        return Message.success().payLoad("users",allUsers);
    }

    /**
     * @Description 添加文章
     * @param article: 前端封装的文章
     * @return
     **/
    @ResponseBody
    @RequestMapping("/add")
    public Message addArticle(@RequestBody Article article)
    {
        articleService.addArticle(article);
        return Message.success();
    }

    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public Message deleteArticleById(@RequestParam("id") int id)
    {
        try
        {
            articleService.deleteArticleById(id);
            return Message.success().payLoad("message","删除文章成功！");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Message.fail().payLoad("message","删除文章失败！");
        }
    }

    @ResponseBody
    @RequestMapping("/update")
    public Message updateArticleById(@RequestBody Article article)
    {
        try
        {
            articleService.updateArticleById(article);
            return Message.success().payLoad("message","修改文章成功！");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return Message.fail().payLoad("message","修改文章失败！");
        }
    }
}
